package com.moli.iov.sys.utils;

import com.moli.iov.sys.constants.Constant;
import com.moli.iov.sys.model.dto.req.PwdDto;
import com.moli.iov.sys.model.po.User;
import com.moli.iov.util.BeanUtils;
import com.moli.iov.util.Md5PwdEncoder;
import com.moli.iov.util.TokenUtil;
import com.moli.iov.util.api.ApiUtils;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

/**
 * <p>
 * 密码工具类
 * </p>
 *
 * @author zql
 * @since 2019/9/11 15:21
 */
@Slf4j
public class PwdUtil {


  /**
   * 生成密码
   * @param password 加密前密码
   * @param salt     盐
   * @return
   */
  public static String createPwd(String password, String salt){
    return Md5PwdEncoder.encodePassword(password, salt);
  }

  /**
   * 生成token
   * @param user
   * @return
   */
  public static String createToken(User user) throws Exception {
    Map<String, String> stringStringMap = convertMap(user);
    return TokenUtil.createJWT(stringStringMap, Constant.TOKEN_EXPIRATION);
  }

  /**
   * user转map
   * @param user
   * @return
   * @throws Exception
   */
  public static Map<String, String> convertMap(User user) throws Exception {
    Map<String, Object> map = BeanUtils.objectToMap(user);
    Map<String, String> tMap = new HashMap<>();

    for(Map.Entry<String, Object> entry: map.entrySet()){
      tMap.put(entry.getKey(), String.valueOf(entry.getValue()));
    }

    return tMap;
  }

  /**
   * 生成密码
   * @param salt
   * @return
   */
  public static PwdDto createPassword(String salt){
    String pwdY = ApiUtils.generateNonceStrLower(Constant.PWD_LENGTH);
    String pwd = createPwd(pwdY, salt);

    return new PwdDto(pwdY, pwd);
  }

  /**
   * 返回解码后的pwd
   * @param pwdPrefix
   * @param pwd
   * @return
   */
  public static String decodePwd(String pwdPrefix, String pwd) {
    log.info("解码前：{}", pwd);
    pwd = pwd.substring(pwdPrefix.length());

    try {
      pwd = new String(Base64Utils.decodeFromString(pwd), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      log.error("解码后的pwd 异常", e);
    }
    log.info("解码后：{}", pwd);
    return pwd;
  }
}
